import {createRouter, RouteRecordRaw, createWebHistory, RouteRecordName} from 'vue-router'
import { store } from '@/store/index';
import {Session} from '@/utils/storage'

import {dynamicRoutes, staticRoutes} from './route'
import {initFrontEndControlRoutes} from './frontEnd'
// 路由多级嵌套数组处理成一维数组
export function formatFlatteningRoutes(routeArr: any[]) {
  if(routeArr.length < 0) return []
  routeArr.forEach((routeItem, index) => {
    if(routeItem.children){
      const curRouteArr = routeArr.slice(0, index+1)
      const updateRouteArr = routeArr.slice(index+1)
      routeArr = curRouteArr.concat(routeItem.children, updateRouteArr)
    }
  })
  return routeArr
}

// 一维数组处理成多级嵌套数组（只保留二级：也就是二级以上全部处理成只有二级，keep-alive 支持二级缓存）
export function formatTwoStageRoutes(routeArr: any[]) {
  if(routeArr.length < 0) return []
  const newRouteArr: any[] = []
  const cacheList: string[] = []
  routeArr.forEach((routeItem: any) => {
    const {path, component, name, redirect, meta} = routeItem
    if(path === '/'){
      newRouteArr.push({
        component, 
        name, 
        redirect, 
        meta,
        children: []
      })
    } else {
      // 判断是否携带params路由参数
      if(path.indexOf('/:') > -1) {
        routeItem.meta['isDynamic'] = true
        routeItem.meta['isDynamicPath'] = routeItem.path
      }
      newRouteArr[0].children.push({...routeItem})
    }
  })
  return newRouteArr
}

// 获取有当前用户权限标识的路由数组，进行对原路由的替换
export function setFilterRouteEnd() {
  const flatRouteList = formatFlatteningRoutes(dynamicRoutes)
  let filterRouteEnd = formatTwoStageRoutes(flatRouteList)
  return filterRouteEnd
}

// 动态添加路由
export function setAddRoute() {
  const getAllRouteList = setFilterRouteEnd()
  getAllRouteList.forEach((route: RouteRecordRaw) => {
    const routeName = route.name as RouteRecordName;
    if(!(router.hasRoute(routeName))){
      router.addRoute(route)
    }
  })
}



// 存储路由数据到vuex
export function setFilterMenuAndCacheTagsViewRoutes(){
  // store.dispatch('routesList/setRoutesList', setFilterHasRolesMenu(dynamicRoutes[0].children, store.state.userInfos.userInfos.roles))
  store.dispatch('routesList/setRoutesList', dynamicRoutes[0].children)

}

// 重置路由
export function resetRoute() {
  const getAllRouteList = setFilterRouteEnd()
  getAllRouteList.forEach((route: RouteRecordRaw) => {
    const routeName = route.name as RouteRecordName;
    router.hasRoute(routeName) && router.removeRoute(routeName)
  })
}

// 创建路由
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: staticRoutes
})

// isRequestRoutes 为 true，则开启后端控制路由，路径：`/src/store/modules/themeConfig.ts`
const { isRequestRoutes } = store.state.themeConfig.themeConfig;

// 前端控制路由：初始化方法，防止刷新时路由丢失
if (!isRequestRoutes) initFrontEndControlRoutes();

router.beforeEach(async(to, from, next) => {
  const token = Session.get('token')

  // 跳转登录页面
  if(to.path === '/login'){
    if(token){
      next('/home');
    } 
    next()
    return
  } 

  // 没有token 跳转到登录页面
  if(!token){
    const params = to.query || to.params
    let url = `/login?redirect=${to.path}`
    if(Object.keys(params).length){
      url+=`&params=${JSON.stringify(params)}`
    }
    next(url)
    Session.clear()
    resetRoute()
    return
  }
  console.log('调整')
  next()
})


export default router